#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

namespace SocketModule
{
    using namespace LogModule;
    using namespace std;

    const static int gbacklog = 16;

    class Socket
    {
    public:
        virtual ~Socket() {}
        virtual void SocketOrDie() = 0;
        virtual void BindOrDie(uint16_t port) = 0;
        virtual void ListenOrDie(int backlog) = 0;
        virtual void Close() = 0;
        virtual shared_ptr<Socket> accept(InetAddr *client) = 0;
        virtual int Recv(string *out) = 0;
        virtual int Send(const string &message) = 0;
        virtual int Connect(const string &server_ip, uint16_t port) = 0;

    public:
        void BuildTcpSocketMethod(uint16_t port, int backlog = gbacklog)
        {
            SocketOrDie();
            //cout<<"2";
            BindOrDie(port);//为啥错？
            //cout<<"1"<<endl;
            ListenOrDie(backlog);
        }
        void TcpClientSocket()
        {
            SocketOrDie();
        }
        void BuildUdpSocketMethod(uint16_t port)
        {
            SocketOrDie();
            BindOrDie(port);
        }
        void UdpClientSocket()
        {
            SocketOrDie();
        }
    };

    const static int defaultnum = -1;
    class TcpSocket : public Socket
    {
    public:
        TcpSocket() : _sockfd(defaultnum)
        {
        }
        TcpSocket(int fd) : _sockfd(fd)
        {
        }
        void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(LogLevel::FATAL) << "socket error";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::INFO) << "socket success";

            int opt = 1;
            setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        }

        void BindOrDie(uint16_t port) override
        {
            InetAddr localaddr(port);
            // 这里报错
            int n = ::bind(_sockfd, localaddr.NetAddrPtr(), localaddr.NetAddrLen());
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "bind error";
                //cout<<"1";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind success";
        }

        void ListenOrDie(int backlog) override
        {
            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "listen error";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "listen success";
        }

        shared_ptr<Socket> accept(InetAddr *client) override
        {
            sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int fd = ::accept(_sockfd, CONV(peer), &len);
            if (fd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                return nullptr;
            }
            client->SetAddr(peer);
            return make_shared<TcpSocket>(fd);
        }

        void Close() override
        {
            if (_sockfd > 0)
                ::close(_sockfd);
        }

        int Recv(string *out) override
        {
            char buffer[1024];
            ssize_t n = ::recv(_sockfd, buffer, sizeof(buffer)-1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }
            return n;
        }

        int Send(const string &message) override
        {
            return ::send(_sockfd, message.c_str(), message.size(), 0);
        }

        int Connect(const string &server_ip, uint16_t port) override
        {
            InetAddr server(server_ip, port);
            int n = connect(_sockfd, server.NetAddrPtr(), server.NetAddrLen());
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "connect error";
                exit(CONNECT_ERR);
            }
            LOG(LogLevel::INFO) << "connect success";
            return n;
        }

    private:
        int _sockfd;
    };
}